package com.gthncz;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ClientDemo {

    private final static String server_host = "127.0.0.1"; // "172.16.3.7";
    private final static int server_port = 65500;

    public static void main(String[] agrs) {
        for (int i=0; i<100000; ++i) {
            Socket socket = null;
            InputStream is = null;
            OutputStream os = null;
            try {
                System.out.printf("Create %d connection: ", i);
                socket = new Socket();
                socket.connect(new InetSocketAddress(server_host, server_port), 1000);
                System.out.printf("port: %d\n", socket.getLocalPort());

                // 发送数据
                os = socket.getOutputStream();
                is = socket.getInputStream();

                String msg = String.format("this is %d socket.", i);
                os.write(msg.getBytes());
                os.flush();
                socket.shutdownOutput(); // 关闭输出流
                System.out.println("Sent msg: " + msg);
                System.out.flush();

                StringBuilder builder = new StringBuilder();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    builder.append(new String(buffer, 0, len));
                }
                socket.shutdownInput();
                System.out.println("Recv msg: " + builder.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) os.close(); // 会导致 Socket 被关闭
                    if (is != null) is.close();
                    if (socket != null) socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
